package com.zhxs.nfcscan.base.app;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import com.zhhd.libdb.ProjectDatabase;
import com.zhxs.nfcscan.base.http.model.RequestHandler;
import com.zhxs.nfcscan.base.http.model.RequestServer;
import com.zhxs.nfcscan.view.DataSyncActivity;
import com.zhxs.utils.LogUtil;
import com.zhxs.utils.SDCardUtil;
import com.zhxs.websocket.WebSocketService;
import com.hjq.bar.TitleBar;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.http.EasyConfig;
import com.hjq.toast.ToastUtils;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mmkv.MMKV;
import com.zhxs.nfcscan.R;
import com.zhxs.nfcscan.base.manager.ActivityManager;
import com.zhxs.nfcscan.base.other.AppConfig;
import com.zhxs.nfcscan.base.other.CrashHandler;
import com.zhxs.nfcscan.base.other.DebugLoggerTree;
import com.zhxs.nfcscan.base.other.TitleBarStyle;
import com.zhxs.nfcscan.base.other.ToastLogInterceptor;
import com.zhxs.nfcscan.base.other.ToastStyle;

import okhttp3.OkHttpClient;
import timber.log.Timber;

/**
 *    author : Android
 *    github : https://github.com/getActivity/
 *    time   : 2018/10/18
 *    desc   : 应用入口
 */
public final class AppApplication extends Application {
    //服务器url
    public static final String KEY_SERVER_URL = "server_url";
    //人员信息列表
    public static final String KEY_PERSON_LIST_INFO = "person_list_info";
    //当前持机人信息
    public static final String KEY_PERSON_INFO = "person_info";
    public static final String KEY_RECORD_INFO = "record_info";
    public static final String DEFAULT_SERVER_URL = "http://192.168.1.200:7777";
    private int activityCount = 0;
    private Intent webSocketServiceIntent;

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.d("onCreate");
        webSocketServiceIntent = new Intent(this, WebSocketService.class);

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                if (activityCount == 0){
                    startService(webSocketServiceIntent);
                }
                activityCount++;
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                activityCount--;
                if (activityCount == 0){
                   stopService(webSocketServiceIntent);
                }
            }
        });
        initSdk(this);

    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }

    /**
     * 初始化一些第三方框架
     */
    public static void initSdk(Application application) {
        // 设置标题栏初始化器
        TitleBar.setDefaultStyle(new TitleBarStyle());
        LogUtil.logLevel(LogUtil.DEBUG_LEVEL_VERBOSE);
//        // 设置全局的 Header 构建器
//        SmartRefreshLayout.setDefaultRefreshHeaderCreator((cx, layout) ->
//                new MaterialHeader(application).setColorSchemeColors(ContextCompat.getColor(application, R.color.common_accent_color)));
//        // 设置全局的 Footer 构建器
//        SmartRefreshLayout.setDefaultRefreshFooterCreator((cx, layout) -> new SmartBallPulseFooter(application));
//        // 设置全局初始化器
//        SmartRefreshLayout.setDefaultRefreshInitializer((cx, layout) -> {
//            // 刷新头部是否跟随内容偏移
//            layout.setEnableHeaderTranslationContent(true)
//                    // 刷新尾部是否跟随内容偏移
//                    .setEnableFooterTranslationContent(true)
//                    // 加载更多是否跟随内容偏移
//                    .setEnableFooterFollowWhenNoMoreData(true)
//                    // 内容不满一页时是否可以上拉加载更多
//                    .setEnableLoadMoreWhenContentNotFull(false)
//                    // 仿苹果越界效果开关
//                    .setEnableOverScrollDrag(false);
//        });

        // 初始化吐司
        ToastUtils.init(application, new ToastStyle());
        // 设置调试模式
        ToastUtils.setDebugMode(AppConfig.isDebug());
        // 设置 Toast 拦截器
        ToastUtils.setInterceptor(new ToastLogInterceptor());

        // 本地异常捕捉
        CrashHandler.register(application);

        // 友盟统计、登录、分享 SDK
//        UmengClient.init(application, AppConfig.isLogEnable());

        // Bugly 异常捕捉
//        CrashReport.initCrashReport(application, AppConfig.getBuglyId(), AppConfig.isDebug());

        // Activity 栈管理初始化
        ActivityManager.getInstance().init(application);

        // MMKV 初始化
        MMKV.initialize(application);

        // 网络请求框架初始化
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .build();
        EasyConfig.with(okHttpClient)
                // 是否打印日志
                .setLogEnabled(AppConfig.isLogEnable())
                // 设置服务器配置
                .setServer(new RequestServer(""))
                // 设置请求处理策略
                .setHandler(new RequestHandler(application))
                // 设置请求重试次数
                .setRetryCount(0)

                .into();

        // 设置 Json 解析容错监听
        GsonFactory.setJsonCallback((typeToken, fieldName, jsonToken) -> {
            // 上报到 Bugly 错误列表
            CrashReport.postCatchedException(new IllegalArgumentException(
                    "类型解析异常：" + typeToken + "#" + fieldName + "，后台返回的类型为：" + jsonToken));
        });

        // 初始化日志打印
        if (AppConfig.isLogEnable()) {
            Timber.plant(new DebugLoggerTree());
        }

        // 注册网络状态变化监听
//        ConnectivityManager connectivityManager = ContextCompat.getSystemService(application, ConnectivityManager.class);
//        if (connectivityManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            connectivityManager.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback() {
//                @Override
//                public void onLost(@NonNull Network network) {
//                    Activity topActivity = ActivityManager.getInstance().getTopActivity();
//                    if (!(topActivity instanceof LifecycleOwner)) {
//                        return;
//                    }
//
//                    LifecycleOwner lifecycleOwner = ((LifecycleOwner) topActivity);
//                    if (lifecycleOwner.getLifecycle().getCurrentState() != Lifecycle.State.RESUMED) {
//                        return;
//                    }
//
//                    ToastUtils.show(R.string.common_network_error);
//                }
//            });
//        }
    }
}